<template>
  <view class="tree-node">
    <view 
      class="node-content" 
      :class="{ 
        'selected': node.id === selectedId, 
        'area-node': node.type === 'area' 
      }"
      :style="{ paddingLeft: (level * 20) + 'px' }"
      @click="handleClick"
    >
      <!-- 展开/收起图标 -->
      <view class="icon-wrapper" v-if="node.type === 'area' && hasChildren">
        <uni-icons 
          :type="expanded ? 'bottom' : 'right'"
          size="14"
          color="#909399"
        />
      </view>
      <view class="icon-wrapper" v-else style="width: 14px;"></view>
      
      <!-- 节点类型图标 -->
      <uni-icons 
        :type="node.type === 'area' ? 'home' : 'water'"
        size="16"
        :color="node.type === 'area' ? '#409eff' : '#67c23a'"
      />
      
      <!-- 节点标签 -->
      <text class="node-label">{{ node.label }}</text>
    </view>
    
    <!-- 子节点 -->
    <view v-if="expanded && hasChildren" class="node-children">
      <tree-item 
        v-for="child in node.children" 
        :key="child.id" 
        :node="child"
        :level="level + 1"
        :selected-id="selectedId"
        @node-click="$emit('node-click', $event)"
      />
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'

const props = defineProps({
  node: {
    type: Object,
    required: true
  },
  level: {
    type: Number,
    default: 0
  },
  selectedId: {
    type: [String, Number],
    default: null
  }
})

const emit = defineEmits(['node-click'])

const expanded = ref(true)

const hasChildren = computed(() => {
  return props.node.children && props.node.children.length > 0
})

const handleClick = () => {
  if (props.node.type === 'meter') {
    // 点击水表节点，触发选择事件
    emit('node-click', props.node)
  } else if (props.node.type === 'area' && hasChildren.value) {
    // 点击区域节点，切换展开/收起状态
    expanded.value = !expanded.value
  }
}
</script>

<style scoped>
.tree-node {
  width: 100%;
}

.node-content {
  display: flex;
  align-items: center;
  padding: 10px 5px;
  border-radius: 4px;
  transition: background-color 0.2s;
  cursor: pointer;
}

.node-content:active {
  background-color: #f5f5f5;
}

.node-content.selected {
  background-color: #ecf5ff;
}

.node-content.area-node {
  font-weight: 500;
}

.icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 5px;
}

.node-label {
  margin-left: 8px;
  font-size: 14px;
  color: #333;
  flex: 1;
}

.node-children {
  width: 100%;
}
</style>